<template>
  <div :key="renderKey">
    <el-card class="account-card">
      <h2 style="margin-bottom: 20px;">我的账户</h2>

      <!-- 未登录 -->
      <div v-if="!isLoggedIn">
        <el-tabs v-model="authTab">
          <el-tab-pane label="登录" name="login">
            <el-form :model="loginForm" label-width="80px">
              <el-form-item label="账号">
                <el-input v-model="loginForm.account" />
              </el-form-item>
              <el-form-item label="密码">
                <el-input v-model="loginForm.password" type="password" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleLogin">登录</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="注册" name="register">
            <el-form :model="registerForm" label-width="80px">
              <el-form-item label="账号">
                <el-input v-model="registerForm.account" />
              </el-form-item>
              <el-form-item label="密码">
                <el-input v-model="registerForm.password" type="password" />
              </el-form-item>
              <el-form-item label="用户名">
                <el-input v-model="registerForm.username" />
              </el-form-item>
              <el-form-item>
                <el-button type="success" @click="handleRegister">注册并登录</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 已登录 -->
      <div v-else>
        <div style="text-align: center; margin-bottom: 20px;">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-change="handleAvatarChange"
            accept="image/*"
          >
            <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div style="margin-top: 10px; font-size: 14px;">点击头像上传</div>
        </div>

        <el-form label-width="100px" :model="userInfo" disabled>
          <el-form-item label="账号">
            <el-input v-model="userInfo.account" />
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="userInfo.username" />
          </el-form-item>
          <el-form-item label="注册时间">
            <el-input v-model="userInfo.registeredAt" />
          </el-form-item>
        </el-form>

        <el-divider />

        <h3>修改密码</h3>
        <el-form :model="passwordForm" ref="pwdForm" label-width="100px">
          <el-form-item label="旧密码">
            <el-input v-model="passwordForm.oldPwd" type="password" />
          </el-form-item>
          <el-form-item label="新密码">
            <el-input v-model="passwordForm.newPwd" type="password" />
          </el-form-item>
          <el-form-item label="确认密码">
            <el-input v-model="passwordForm.confirmPwd" type="password" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePassword">修改密码</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'AccountPage',
  data() {
    return {
      renderKey: Date.now(),
      authTab: 'login',
      isLoggedIn: false,
      loginForm: {
        account: '',
        password: ''
      },
      registerForm: {
        account: '',
        password: '',
        username: ''
      },
      userInfo: {
        account: '',
        username: '',
        registeredAt: '',
        avatar: ''
      },
      passwordForm: {
        oldPwd: '',
        newPwd: '',
        confirmPwd: ''
      }
    };
  },
  mounted() {
    const user = JSON.parse(localStorage.getItem('currentUser'));
    if (user) {
      this.userInfo = user;
      this.isLoggedIn = true;
      this.syncAvatarToLayout(user.avatar);
    }

    this.$root.$on('user-logout', () => {
      this.isLoggedIn = false;
      this.userInfo = {
        account: '',
        username: '',
        registeredAt: '',
        avatar: ''
      };
      this.renderKey = Date.now(); // 🔁 强制刷新视图
    });
  },
  methods: {
    handleLogin() {
      const stored = JSON.parse(localStorage.getItem('userList') || '[]');
      const user = stored.find(
        u =>
          u.account === this.loginForm.account &&
          u.password === this.loginForm.password
      );
      if (user) {
        this.userInfo = { ...user };
        this.isLoggedIn = true;
        localStorage.setItem('currentUser', JSON.stringify(user));
        this.syncAvatarToLayout(user.avatar);
        this.$message.success('登录成功');
      } else {
        this.$message.error('账号或密码错误');
      }
    },
    handleRegister() {
      const list = JSON.parse(localStorage.getItem('userList') || '[]');
      if (list.some(u => u.account === this.registerForm.account)) {
        this.$message.error('账号已存在');
        return;
      }
      const newUser = {
        ...this.registerForm,
        registeredAt: new Date().toLocaleString(),
        avatar: ''
      };
      list.push(newUser);
      localStorage.setItem('userList', JSON.stringify(list));
      localStorage.setItem('currentUser', JSON.stringify(newUser));
      this.userInfo = newUser;
      this.isLoggedIn = true;
      this.syncAvatarToLayout('');
      this.$message.success('注册成功并已登录');
    },
    handleAvatarChange(e) {
      const file = e.raw;
      const reader = new FileReader();
      reader.onload = () => {
        const base64 = reader.result;
        this.userInfo.avatar = base64;
        localStorage.setItem('currentUser', JSON.stringify(this.userInfo));
        this.syncAvatarToLayout(base64);
        const list = JSON.parse(localStorage.getItem('userList') || '[]');
        const idx = list.findIndex(u => u.account === this.userInfo.account);
        if (idx !== -1) {
          list[idx].avatar = base64;
          localStorage.setItem('userList', JSON.stringify(list));
        }
        this.$message.success('头像上传成功');
      };
      reader.readAsDataURL(file);
    },
    syncAvatarToLayout(base64) {
      this.$root.$emit('update-avatar', base64);
    },
    updatePassword() {
      if (this.passwordForm.oldPwd !== this.userInfo.password) {
        this.$message.error('旧密码不正确');
        return;
      }
      if (this.passwordForm.newPwd !== this.passwordForm.confirmPwd) {
        this.$message.error('两次密码不一致');
        return;
      }

      this.userInfo.password = this.passwordForm.newPwd;
      localStorage.setItem('currentUser', JSON.stringify(this.userInfo));
      const list = JSON.parse(localStorage.getItem('userList') || '[]');
      const idx = list.findIndex(u => u.account === this.userInfo.account);
      if (idx !== -1) {
        list[idx].password = this.userInfo.password;
        localStorage.setItem('userList', JSON.stringify(list));
      }

      this.passwordForm.oldPwd = '';
      this.passwordForm.newPwd = '';
      this.passwordForm.confirmPwd = '';
      this.$message.success('密码修改成功');
    }
  }
};
</script>

<style scoped>
.account-card {
  max-width: 600px;
  margin: 40px auto;
}
.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}
.avatar-uploader .el-upload {
  display: inline-block;
  cursor: pointer;
}
.avatar-uploader-icon {
  font-size: 32px;
  color: #aaa;
  line-height: 100px;
  text-align: center;
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
  border-radius: 50%;
}
</style>
